package com.dudu.service.impl;

import java.util.Calendar;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.dudu.access.EcpUtils;
import com.dudu.access.IMSTXUtils;
import com.dudu.access.ImsUtils;
import com.dudu.bean.MeetInfoBean;
import com.dudu.enumeration.AbilityTypeEnum;
import com.dudu.service.IConferenceEndService;
import com.dudu.service.ILogService;
import com.dudu.service.IMeetInfoService;
import com.dudu.utils.DateUtils;
import com.dudu.utils.ProperyResource;
import com.huawei.mediax.webservice.types.LogoutResponseDocument;
import com.huawei.mediax.webservice.types.RemoveConferenceResponseDocument;

import core.CoreDao;
import core.CoreDaoInvoke;

/**
 * 多方通话--结束通话
 * 
 * @author weidong
 * 
 */
public class ConferenceEndServiceImpl implements IConferenceEndService {
    // 用于查询数据用
    private CoreDao coreDao = CoreDaoInvoke.getInstance();
    private static final Logger log = core.util.Logger.getLogger(ConferenceEndServiceImpl.class.getSimpleName());
    // 用于记录相应接口调用的日志
    private ILogService logService = new LogService();

    /**
     * 用于多方通话结束通话
     * 
     * @param sessionId
     *            会议标识
     * @return
     */
    @Override
    public JSONObject doEnd(String sessionId) {
	// 用于最后返回值
	JSONObject object = new JSONObject();
	try {
	    IMeetInfoService meetInfoService = new MeetInfoServiceImpl();
	    // 查询会议详情信息-根据会议sessionId-用于判断此通话的通话类型是哪个通道接入
	    MeetInfoBean meetInfo = meetInfoService.queryMeetImsBySessionId(coreDao, sessionId);
	    String abilityType = "";
	    if (meetInfo != null) {
		// 获取通话类型
		abilityType = meetInfo.getAbility_type();
		// 判断如果通道类型是IMS多方通话，则调用IMS多方通话接口
		if (AbilityTypeEnum.TALKSV2.getKey().equals(abilityType)) {
		    // 多方通话--结束通话
		    object = doEndTalksV2(sessionId);
		} else if (AbilityTypeEnum.ECPMEET.getKey().equals(abilityType)) {
		    // ECP多方通话--结束通话
		    object = doEndECP(sessionId);
		} else if (AbilityTypeEnum.SCONFERENCE.getKey().equals(abilityType)) {
		    String soapSessionId = meetInfo.getRoom_id();
		    // 判断如果没有取到soap相应的sessionId，则报异常
		    if (soapSessionId == null || soapSessionId.equals("")) {
			object.put("result", "-1");
			object.put("errorMsg", "未找到相应的上级SOAPSessionId！");
			object.put("describe", "sessionId不存在");
			object.put("code", "0006");
		    } else {
			object = doEndSOAP(soapSessionId, sessionId);
		    }
		} else {
		    object.put("result", "-1");
		    object.put("errorMsg", "未配置对应通道！voice_type:" + abilityType);
		    object.put("describe", "未配置线路");
		    object.put("code", "0010");
		}

	    } else {
		object.put("result", "-1");
		object.put("describe", "sessionId不存在");
		object.put("code", "0006");
	    }
	} catch (Exception e) {
	    object.put("result", "-1");
	    object.put("errorMsg", "错误=" + e);
	    object.put("describe", "多方通话结束通话异常");
	    object.put("code", "0307");
	}

	return object;
    }

    /**
     * IMS智能多方通话结束通话
     * 
     * @param sessionId
     *            会议标识
     * @return
     */
    private JSONObject doEndTalksV2(String sessionId) {
	// 用于后面返回值
	JSONObject object = new JSONObject();
	// 开始结束会议
	try {
	    // 调用IMS智能多方通话，踢出通话人接口
	    object = ImsUtils.talksV2AllStop(sessionId, true);
	    if (!"0".equals(object.get("result"))) {
		object.put("result", "-1");
		object.put("errorMsg", "通道会议结束失败");
		object.put("describe", "多方通话结束通话异常");
		object.put("code", "0307");
	    }
	} catch (Exception e) {
	    object.put("result", "-1");
	    object.put("describe", "多方通话结束通话异常");
	    object.put("code", "0307");
	}
	return object;
    }

    /**
     * IMS专业会议结束通话
     * 
     * @param SOAPSessionId
     *            会议标识
     * @param conferenceId
     *            会议室标识
     * @return
     */
    private JSONObject doEndSOAP(String SOAPSessionId, String conferenceId) {
	// 最终返回的值
	JSONObject object = new JSONObject();
	try {
	    // 用于记录发起会话所用时间
	    // 开始时间的时间戳
	    long begin = 0;
	    // 结束时间的时间戳
	    long end = 0;
	    // 时间差值
	    double during;
	    // 通话发起时间
	    String currentTime = DateUtils.getCurrentTime();
	    String results = "";

	    // 开始时间
	    begin = Calendar.getInstance().getTimeInMillis();
	    // 根据号码获取相应信息
	    RemoveConferenceResponseDocument doc = IMSTXUtils.removeConference(SOAPSessionId, conferenceId);
	    // 调用结束时间
	    end = Calendar.getInstance().getTimeInMillis();
	    if (doc != null && doc.getRemoveConferenceResponse() != null) {
		if (doc.getRemoveConferenceResponse().getCode() == 200) {
		    results = "0";
		    // 退出登录
		    LogoutResponseDocument docEnd = IMSTXUtils.logout(SOAPSessionId);
		    // 判断是否正常退出
		    if (docEnd != null && docEnd.getLogoutResponse() != null) {

			if (docEnd.getLogoutResponse().getCode() == 200) {
			    object.put("result", "0");
			    object.put("describe", "退出成功");
			    object.put("code", "0000");
			} else {
			    object.put("result", "-1");
			    object.put("describe", "退出失败");
			    object.put("code", "0023");
			}

		    } else {
			object.put("result", "-1");
			object.put("describe", "退出发生异常");
			object.put("code", "0100");
		    }
		} else {
		    results = doc.getRemoveConferenceResponse().getCode() + "";
		    object.put("result", doc.getRemoveConferenceResponse().getCode() + "");
		    object.put("describe", "关闭会议失败");
		    object.put("code", "0023");
		}
	    } else {
		results = doc.getRemoveConferenceResponse().getCode() + "";
		object.put("result", doc.getRemoveConferenceResponse().getCode() + "");
		object.put("describe", "关闭会议失败");
		object.put("code", "0023");
	    }
	    // 发起通话的日志
	    try {
		during = Double.valueOf((end - begin)) / 1000;
		// 获取发起通话的URL
		StringBuffer urlBuffer = new StringBuffer("IMS专业会议");
		// 拼相应的参数
		urlBuffer.append("?SOAPSessionId=");
		urlBuffer.append(SOAPSessionId);
		logService.logIms(during, AbilityTypeEnum.SCONFERENCE.getKey() + "ConferenceEnd", urlBuffer.toString(), results, results, currentTime, "SOAP", "");
	    } catch (Exception e) {
		log.info("------IMS专业会议中踢出采育人日志异常！----" + e);
	    }
	} catch (Exception e) {
	    object.put("result", "-1");
	    object.put("describe", "关闭会议异常！");
	    object.put("code", "0100");
	    log.error("关闭会议异常：" + e.getMessage());
	}
	return object;
    }

    /**
     * ECP会议结束通话
     * 
     * @param sessionId
     *            会议标识
     * @return
     */
    private JSONObject doEndECP(String sessionId) {
	// 最终返回的值
	JSONObject object = new JSONObject();
	try {
	    // 用于记录发起会话所用时间
	    // 开始时间的时间戳
	    long begin = 0;
	    // 结束时间的时间戳
	    long end = 0;
	    // 时间差值
	    double during;
	    // 通话发起时间
	    String currentTime = DateUtils.getCurrentTime();
	    // 开始时间
	    begin = Calendar.getInstance().getTimeInMillis();
	    // 结束会议
	    String result = EcpUtils.endConference(sessionId);
	    // 开始时间
	    end = Calendar.getInstance().getTimeInMillis();
	    Document doc = DocumentHelper.parseText(result);
	    Element root = doc.getRootElement();
	    // 获取查询结果
	    // 获取是否成功标识
	    String results = root.elementTextTrim("result");
	    // 发起通话的日志
	    try {
		during = Double.valueOf((end - begin)) / 1000;
		// 获取发起通话的URL
		StringBuffer urlBuffer = new StringBuffer(ProperyResource.getEcp_Status_Url());
		// 拼相应的参数
		urlBuffer.append("?ConferenceIdentifier=");
		urlBuffer.append(sessionId);
		logService.logIms(during, AbilityTypeEnum.ECPMEET.getKey() + "End", urlBuffer.toString(), result, results, currentTime, "ECP", "");
	    } catch (Exception e) {
		log.info("------ECP多方通话过程中新增成员日志异常！----");
	    }
	    if (results.equals("1100")) {
		object.put("sessionId", sessionId);
		object.put("result", "0");
		object.put("describe", "结束会议成功");
		object.put("code", "0000");
	    } else {
		object.put("result", "-1");
		object.put("describe", "结束会议错误：" + result);
		object.put("code", "0023");
	    }
	} catch (Exception e) {
	    log.error("结束会议异常：" + e.getMessage());
	    object.put("result", "-1");
	    object.put("describe", "结束会议错误：" + e);
	    object.put("code", "0023");
	}
	return object;
    }

}
